// 主界面
;define(function(require, exports, module) {
    'use strict';
    var util = require("util");
    var base = require("base");
    var leftMenu = require("../leftMenu/leftMenu");
    var topMenu = require("../topMenu/topMenu");
    var router = require("../hash/pageRouter");
    var footer = require("../footer/footer_main");
    var settlementDetail_css = require("./settlementDetail.css");
    var html_charge_day = require("./htmlChargeDay.html");
    var dialog = require("dialog");
    var validate = require("validate");
    var constant = require("constant");
    var databind = require("databind");
    var firstVisited = 0;
    var tools = require("tools");
    var auditState;
    var leftM;
    var year = new Number; // 账单年
    var month = 0; // 账单月
    var day = new Number; 
    var monthEarningNumber;
    var enterpriseId;
    var dateStart; // "2017-11-20"
    var dateEnd; // "2017-12-20"
    var financeNumber;
    var pageIndex = 0,
        pageSize = 10,
        totalPageCount = 1,
        totalRecordCount = 0; //分页初始化
        
    var init = function(page){
    	$("#header").html(require("../topMenu/topMenu.html"));
    	firstVisited = base.getUrlParam("firstVisited");
    	leftM = auditState = base.getUrlParam("leftM");
    	leftM = leftM == null?4:leftM;
    	footer.init();  	
    	
    	year = base.getUrlParam("year");
    	month = base.getUrlParam("month");
    	monthEarningNumber = base.getUrlParam("monthEarningNumber");
    	enterpriseId = base.getUrlParam("enterpriseId");
    	leftM = leftM == null?4:leftM;
    	footer.init();  	
    	$("#footer").removeClass("none");

    	leftMenu.init(leftM);
    	
    	$(".serviceFeeIncome").parents("li.leftMenu-item").addClass("leftMenu-open");
    	$(".leftMenu-item").removeClass("leftMenu-active");
    	$(".serviceChargeSettlement").addClass("leftMenu-active");
    	
    	topMenu.init(2);
    	$(".footer").removeClass("none");
    	
    	showCenterYearMonth(false);
    	inquiryMonthEarningDetail(year, month, function(data) {
    		
    	});
    	inquiryMonthEarningDetailList();
		initEvent();
		router.init();
		
		if(firstVisited != 1){
			$(".table-section").removeClass("none");
		}
    };
    
	var initEvent = function(){
		// 详情
		$("#settlementDetail").on("click", ".table_details_link1", function() {
			var monthEarningDetailId = $(this).parent("tr.tr_style").attr("monthEarningDetailId");
			financeNumber = $(this).parent("tr.tr_style").attr("financeNumber");
			var ii = layer.open({
			  title: ' ',
			  type: 1,
			  skin: 'layui-layer-rim', //加上边框
			  area: ['750px', '900px'], //宽高
			  content: html_charge_day,
			  btn: ['', ''],
			  yes: function(){
			  	
			  }
			});
			
			// 弹出框样式
			var $chargeDayContentPar = $(".chargeDayContent").parent();
			$chargeDayContentPar.siblings("div.layui-layer-btn").remove();
			$chargeDayContentPar.siblings("div.layui-layer-title").css("background-color", "#0099FA");
			
			// 系统参数-结息日
			inquireSystemParamByName();
			
			// 显示年月日期
			showCenterYearMonth(true);
	    	
	    	// 月份向前或向后
	    	// 向前
			$(".chargeDayContent").on("click", ".forward", function() {
				forwardOrBackward(true, true);
				//某月日账单列表
				inquireMonthDaysEarningPageList();
			})
			
			// 向后
			$(".chargeDayContent").on("click", ".backward", function() {
				forwardOrBackward(false, true);
				//某月日账单列表
				inquireMonthDaysEarningPageList();
			})
			
			//融资详情
			inquiryMonthFinancingDetail(monthEarningDetailId);
			//某月日账单列表
			inquireMonthDaysEarningPageList();
			
		});
		
		// 向前
		$("#settlementDetail").on("click", ".forward", function() {
			forwardOrBackward(true, false);
		})
		
		// 向后
		$("#settlementDetail").on("click", ".backward", function() {
			forwardOrBackward(false, false);
		})
		
		// 查询融资列表信息
		$("#settlementDetail").on("click", "#inquiryMonthEarningDetailList", function() {
			var financeNumber = $("#settlementDetail input[name='financeNumber']").val();
			var productType = $("#settlementDetail select[name='productType']").val();
			inquiryMonthEarningDetailList(financeNumber, productType);
		})
		
		// 返回
		$("#settlementDetail").on("click", ".goBack", function() {
			location.href = "../client/serviceChargeSettlement.html";
		})
		
		//按业务查询融资信息列表
		$("#settlementDetail").on("click", ".productTypeFree", function() {
			var financeNumber = null;
			var productType = $(this).attr("productType");
			inquiryMonthEarningDetailList(financeNumber, productType);
			
			// 显示全部
			$("#settlementDetail .showAllFinance").show();
		})
		
		// 显示全部
		$("#settlementDetail").on("click", ".showAllFinance", function() {
			var financeNumber = null;
			var productType = null;
			inquiryMonthEarningDetailList(financeNumber, productType);
			
			// 显示全部
			$("#settlementDetail .showAllFinance").hide();
		})
		
		// 查找
		$("#settlementDetail").on("click", ".table-search-button", function() {
			var financeNumber = $("#settlementDetail input[name='financeNumber']").val();
			var productType = $("#settlementDetail select[name='productType']").val();
			inquiryMonthEarningDetailList(financeNumber, productType);
		})
		
		// 月账单确认
		$("#settlementDetail").on("click", ".table-confirm-button", function() {
			confirmMonthEarningDetail();
		})
		
		// 重新计算月账单
		$("#settlementDetail").on("click", ".table-compute-button", function() {
			reCacluMonthInterest();
		})
		
		// 代采代销导出
		$("#settlementDetail").on("click", ".table-export5-button", function() {
//			exportInterestNotice(5);
			window.open("/finance/api/v1.0/exportInterestNotice.json?month=" + month + "&year=" + year + "&productType=" + 5 + "&enterpriseId=" + enterpriseId);
		})
		
		// 舱单质押导出
		$("#settlementDetail").on("click", ".table-export2-button", function() {
//			exportInterestNotice(2);
			window.open("/finance/api/v1.0/exportInterestNotice.json?month=" + month + "&year=" + year + "&productType=" + 2 + "&enterpriseId=" + enterpriseId);
		})
    };
    
    var inquiryMonthEarningDetailList = function(financeNumber, productType) {
    	base.fnAjax({
			action: "inquiryMonthEarningDetailList.json",
			async: false,
			nocode: true,
			oData: {
				/*pageIndex: pageIndex,
                pageSize: pageSize,*/
                year: year,
                month: month,
                enterpriseId: enterpriseId,
                financeNumber: financeNumber,
                productType: productType
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("getValueByKey", constant.getValueByKey);
					juicer.register("formatCurrency", tools.formatCurrency);
					
					var tpl = $("#monthFinancingList").html();
                    var html = juicer(tpl, data);
                    $("#monthFinancingListBody").html(html);
                    
                    totalPageCount = data.totalPageCount;
                    totalRecordCount = data.totalRecordCount;
                    base.pageControl(
                    	$("#monthFinancingPage"),
                        totalRecordCount,
                        data.pageIndex,
                        data.pageSize,
                        function(p) {
                            pageIndex = p;
                            inquiryMonthEarningDetailList();
                    });
                    
                    // 融资编号
                    $("#financeNumber").unbind("click").click(function() {
						router.route("financing/financingDetailInfo.html?financeId=" + $(this).parents("tr").attr("financeId"));
					});
					
					// 起息日 结息日 结息周期
					$("#settlementDetail .freeStart").text(dateStart);
					$("#settlementDetail .freeEnd").text(dateEnd);
				}else {
					base.alert(2, data.message);
				}
			}
		})
    	
    };
    
    //月份向前或向后
    var forwardOrBackward = function(forward, isChargeDay) {
    	var yearLater;
    	var monthLater;
    	var yearMonthLater;
    	
    	// 1. 计算中间年月
    	if(forward == true) { //向前
    		monthLater = month + 1;
    		if(monthLater > 1 && monthLater < 13) {
    			yearLater = year;
    		}else if(monthLater == 13) {
    			monthLater = 1;
    			yearLater = year + 1;
    		}
    	}else { // 向后
    		monthLater = month - 1;
    		if(monthLater == 0) {
    			monthLater = 12;
    			yearLater = year - 1;
    		}else if(monthLater > 0 && monthLater < 12) {
    			yearLater = year;
    		}
    	}
    	
    	if(isChargeDay == false) { // 非弹出框
	    	inquiryMonthEarningDetail(yearLater, monthLater, function(data) {
	    		if(data.datas.length == 0) {
	    			base.alert(2, "没有账单了");
	    			return;
	    		}else {
	    			//显示中间年月和前后月份和账单起始日期
					year = yearLater;
					month = monthLater; 
					showCenterYearMonth(false);
	    			//获取该企业该月融资列表
	    			inquiryMonthEarningDetailList();	
	    		}
	    	});
    	}else if (isChargeDay == true) {
    		year = yearLater;
			month = monthLater; 
			showCenterYearMonth(false);
			showCenterYearMonth(true);
    	}
    	
    };
    
    var inquiryMonthEarningDetail = function(yearLater, monthLater, callback) {
    	base.fnAjax({
			action: "inquiryMonthEarningDetail.json",
			async: true,
			nocode: true,
			oData: {
				monthEarningNumber: monthEarningNumber,
				enterpriseId: enterpriseId,
				year: yearLater,
				month: monthLater
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("formatCurrency", tools.formatCurrency);
					if(data.datas.length == 0) {
						callback(data);
						return;
					}else {
						// 账单汇总信息
						var tpl = $("#billInfoCollectTemp").html();
	                    var html = juicer(tpl, data);
	                    $("#billInfoCollectBody").html(html);
	                    
	                    // 汇总信息- 业务类型
	                    var tpl = $("#billInfoProductCollectTemp").html();
	                    var html = juicer(tpl, data);
	                    $("#billInfoProductCollectBody").html(html);
	                    
	                    //  本月服务费
	                    $("#settlementDetail #bulkstockIntrerstTotal").text(tools.formatCurrency(data.datas[0].repayingFee));
					}
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    var showCenterYearMonth = function(isChargeDay) { // 是否是弹框中日期
    	var monthBackward;
    	var monthForward;
    	var monthCenter;
    	var yearBackward;
    	
    	if(month == 1) {
    		yearBackward = year - 1;
    		monthBackward = 12;
    		monthForward = 2;
    	}else if(month == 12) {
    		yearBackward = year;
    		monthBackward = 11;
    		monthForward = 1;
    	}else if(month > 1 && month < 12) {
    		yearBackward = year;
    		monthBackward = parseInt(month) - 1;
    		monthForward = parseInt(month) + 1;
    	}
    	//月前加“0”
    	if(month < 10) {
    		monthCenter = "0" + month;
    	}else {
    		monthCenter = month;
    	}
    	if(monthBackward < 10) {
    		monthBackward = "0" + monthBackward;
    	}
    	if(monthForward < 10) {
    		monthForward = "0" + monthForward;
    	}
    	
    	if(isChargeDay == false) { //非弹框
    		$("#settlementDetail .center").html(year + "年" + monthCenter + "月");
	    	$("#settlementDetail .backMonth").html(monthBackward + "月");
	    	$("#settlementDetail .forwMonth").html(monthForward + "月");
    	}else if(isChargeDay == true) {
    		dateStart = yearBackward + "-" + monthBackward + "-" + day;
    		dateEnd = year + "-" + month + "-" + day;
    		$(".chargeDayContent .center").html(year + "年" + monthCenter + "月");
	    	$(".chargeDayContent .backMonth").html(monthBackward + "月");
	    	$(".chargeDayContent .forwMonth").html(monthForward + "月");
    	}

    }
    
    // 获取融资详情信息
    var inquiryMonthFinancingDetail = function(monthEarningDetailId) {
    		base.fnAjax({
			action: "inquiryMonthEarningDetailFinance.json",
			async: true,
			nocode: true,
			oData: {
                monthEarningDetailId: monthEarningDetailId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("formatCurrency", tools.formatCurrency);
					juicer.register("getValueByKey", constant.getValueByKey);
					
					var tpl = $("#monthFinancingDetailTemp").html();
                    var html = juicer(tpl, data);
                    $("#monthFinancingDetailBody").html(html);
                    $(".chargeDayContent td[name='monthEarningNumber']").text($("#settlementDetail td[name='monthEarningNumber']").text());
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    // 获取某月日收益列表
    var inquireMonthDaysEarningPageList = function() {
    		base.fnAjax({
			action: "inquireMonthDaysEarningPageList.json",
			async: true,
			nocode: true,
			oData: {
				pageIndex: pageIndex,
                pageSize: pageSize,
                earningDateStart: dateStart,
                earningDateEnd: dateEnd,
                financeNumber: financeNumber
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("getValueByKey", constant.getValueByKey);
					juicer.register("formatCurrency", tools.formatCurrency);
					
					var tpl = $("#monthDaysEarningList").html();
                    var html = juicer(tpl, data);
                    $("#monthDaysEarningBody").html(html);
                    
                    totalPageCount = data.totalPageCount;
                    totalRecordCount = data.totalRecordCount;
                    base.pageControl(
                    	$("#monthDaysEarningPage"),
                        totalRecordCount,
                        data.pageIndex,
                        data.pageSize,
                        function(p) {
                            pageIndex = p;
                            inquireMonthDaysEarningPageList();
                    });
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    // 系统参数-结息日
    var inquireSystemParamByName = function() {
    		base.fnAjax({
			action: "inquireSystemParamByName.json",
			async: false,
			nocode: true,
			oData: {
				paramName: "结息日"
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					day = data.datas[0].paramValue;
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    // 月账单确认
    var confirmMonthEarningDetail = function() {
    		base.fnAjax({
			action: "confirmMonthEarningDetail.json",
			async: true,
			nocode: true,
			oData: {
				monthEarningId: $("#settlementDetail input[name='monthEarningId']").val()
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					inquiryMonthEarningDetail();
					base.alert(1, "确认成功");
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    // 重新计算月账单
    var reCacluMonthInterest = function() {
    		base.fnAjax({
			action: "reCacluMonthInterest.json",
			async: true,
			nocode: true,
			oData: {
				year: year,
				month: month,
				enterpriseName: $("#settlementDetail td[name='enterpriseName']").text()
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "重新计算月账单成功");
					$.setTimeout(function() {
						inquiryMonthEarningDetailList();
    					inquiryMonthEarningDetail();
					}, 3000);
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    // 导出
    var exportInterestNotice = function(productType) {
    		base.fnAjax({
			action: "exportInterestNotice.json",
			async: true,
			nocode: true,
			oData: {
				year: year,
				month: month,
				productType: productType,
				enterpriseId: enterpriseId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "导出成功");
				}else {
					base.alert(2, data.message);
				}
			}
		})
    };
    
    return {
        init:init
    };
});